package com.itlhc.controller;

import com.google.gson.Gson;
import com.itlhc.pojo.Cookies;
import com.itlhc.pojo.User;
import com.itlhc.service.UserService;
import com.itlhc.tools.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
public class UserController {

    @Autowired
    @Qualifier("UserServiceImpl")
    private UserService userService;


    @RequestMapping("/login")
    public String loginUser(HttpServletRequest request, HttpServletResponse response, Model model) throws UnsupportedEncodingException {
        System.out.println("login ============ " );
        //获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //添加 Cookie
        userService.addCookie(username,password,response,request);


        System.out.println("用户名："+username);
        System.out.println("密码："+password);
        //调用service方法，进行用户匹配
        User user = userService.loinUser(username, password);
        //登录成功
        if(null != user){
            //放入session
            request.getSession().setAttribute(Constants.USER_SESSION, user);
            //页面跳转
            return "index";
        }else{
            //页面跳转（login.jsp）带出提示信息--转发
            //request.setAttribute("error", "用户名或密码不正确");
            //request.getRequestDispatcher("login.jsp").forward(request, response);
            model.addAttribute("error","用户名或密码不正确");
            return "error";
        }
    }


    /**
     * 获取 Cookie中的信息
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/getCookie")
    @ResponseBody
    public String getCookie(HttpServletRequest request)throws IOException {
        /*String username = "";
        String password = "";
        Cookie[] cookies = request.getCookies();*/
        /*if(cookies!=null&&cookies.length>0){
            //遍历Cookie
            for(int i=0;i<cookies.length;i++){
                Cookie cookie = cookies[i];
                //此处类似与Map有
                if("username".equals(cookie.getName())){
                    username = cookie.getValue();
                }
                if("password".equals(cookie.getName())){
                    password = cookie.getValue();
                }
            }
        }
*/

        Cookie[] cookies = request.getCookies();
        //自己定义的javabean Cookies
        Cookies cookies1 = new Cookies();
        for(Cookie cookie :cookies ){
            //System.out.println(c.getName()+"--->"+c.getValue());
            //此处类似与Map有
            if("username".equals(cookie.getName())){
                cookies1.setLoginAccount(cookie.getValue());
            }
            if("password".equals(cookie.getName())){
                cookies1.setLoginPassword(cookie.getValue());
            }
        }

        Gson gson = new Gson();
        System.out.println("nnnn:"+cookies1.getLoginAccount());
        ModelMap modelMap = new ModelMap();
        modelMap.put("username",cookies1.getLoginAccount());
        modelMap.put("password",cookies1.getLoginPassword());
        System.out.println("ggggg:"+gson.toJson(modelMap));
        return gson.toJson(modelMap);
    }

    @RequestMapping("/logout")
    public String Logout(HttpServletRequest request){
        //清除session
        request.getSession().removeAttribute(Constants.USER_SESSION);
        return "redirect:login.jsp";
    }
}
